package org.sunshine.miracle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.InputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Commons {

    public static final Log LOGGER = LogFactory.getLog(Commons.class);

    /**
     * If you do not specify an absolute path, the file will be searched automatically in the following locations:
     * <ul>
     * <li>in the current directory</li>
     * <li>in the user home directory</li>
     * <li>in the classpath</li>
     * </ul>
     *
     * @param path path to search
     * @return null if file was not found, else the inputStream of the file.
     * @throws java.io.IOException if the file reading failed.
     */
    public static InputStream getFileAsInputStream(String path) throws IOException {
        if (Commons.LOGGER.isDebugEnabled()) Commons.LOGGER.debug("Searching file:  " + path);
        File file = new File(path);
        if (file.exists()) {
            if (Commons.LOGGER.isDebugEnabled()) Commons.LOGGER.debug("File found under path:  " + file.getAbsolutePath());
            return new FileInputStream(file);
        }
        String userHome = System.getProperty("user.home");
        file = new File(userHome + File.separator + path);
        if (file.exists()) {
            if (Commons.LOGGER.isDebugEnabled()) Commons.LOGGER.debug("File found under path:  " + file.getAbsolutePath());
            return new FileInputStream(file);
        }

        InputStream inputStream = Commons.class.getResourceAsStream(path);
        if (inputStream != null) {
            if (Commons.LOGGER.isDebugEnabled()) Commons.LOGGER.debug("File found in class path:  " + path);
        } else {
            if (Commons.LOGGER.isDebugEnabled()) Commons.LOGGER.debug("File '" + path + "'not found.");
        }

        return inputStream;
    }


    /**
     * Close provided sql object.
     *
     * @param toClose sql item to close.
     */
    public static void close(Object toClose) {
        if (toClose == null) return;
        try {
            if (toClose instanceof Connection) {
                Connection connection = (Connection) toClose;
                connection.close();
            }

            if (toClose instanceof Statement) {
                Statement statement = (Statement) toClose;
                statement.close();
            }

            if (toClose instanceof ResultSet) {
                ResultSet resultSet = (ResultSet) toClose;
                resultSet.close();
            }

        } catch (SQLException e) {
            Commons.LOGGER.warn("Exception during closing sql object.", e);
        }

        toClose = null;

    }


}
